const App = {
  mixins: [Save],
  //配置文件，路径/utils/mixins.js



  data() {
    return {
      ID_Card: [],
      options: [],
      dataForm: {

      },
      dataForm1: {

      },
      rules: {
        // 身份证编号验证（空值+格式）
        ID_Card_Number: [
          {
            required: true,
            message: "身份证编号不能为空",
            trigger: "blur",
          },
          {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: "身份证格式不正确",
            trigger: "blur",
          },
        ],


      },
      Manager: [],
      Nation: [],
      Ducation: ducation(),
      city: [],
      cityValue: [],
      Category: [],
      is: false,
    };
  },

  mounted() {

    // 解析URL参数
    const query = this.aaa(window.location.href);
    if (query && query.data) {
      this.dataForm = JSON.parse(query.data);
    } else {
      console.error("No 'data' parameter found in the URL.");
    }
    this.action = query.action || 'Add';

    // 如果有身份证参数，加载数据
    if (query.id_card) {
      try {
        this.loadEditData(query.id_card);
      } catch (error) {
        console.log('loadEditData方法未查到');

      }

    }
    // this.getCategory();
    this.getData1();
  },

  watch: {

    dataForm(val) {
      console.log('dataForm被改变', val);

    }
  },
  methods: {
    aaa(url) {
      const query = {};
      const params = url.split('?')[1]; // 获取 URL 中的查询字符串部分
      if (params) {
        params.split('&').forEach(param => {
          const [key, value] = param.split('=');
          query[decodeURIComponent(key)] = decodeURIComponent(value);
        });
      }
      return query;
    },
    shibie(val) {
      if (this.action == 'Add') {
        // 解析URL参数
        const query = getQueryObject(window.location.href);
        this.action = query.action || 'Add';

        // 如果有身份证参数，加载数据
        if (query.id_card) {
          this.loadEditData(query.id_card);
        }



        this.getCategory();

        if (tags.length > 0) {
          this.childDataForm = tags.map(tag => ({
            ...tag,
            Row_Status: '0' // 标记为已存在数据
          }));
        }
      }

      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableName`,
        method: "post",
        data: {
          Data: "personal_information", //表名
          Condition: "ID_Card_Number='" + val + "'",
        },
        success: (res) => {
          if (res.length == 1) {
            this.dataForm1 = res[0];
            this.cityValue = [this.dataForm1.RR_Province_Number, this.dataForm1.RR_City_Number, this.dataForm1.RR_County_Nubmer, this.dataForm1.RR_Town_Number];
            this.is = false;
          } else {
            this.is = true;
          }
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest)
        },
      });
    },
    changeCity(val) {
      if (val.length > 0) {
        let Province = this.city.filter(i => i.value == val[0])[0];
        let City = Province.children.filter(i => i.value == val[1])[0];
        let County = City.children.filter(i => i.value == val[2])[0];
        let Town = County.children.filter(i => i.value == val[3])[0];
        this.dataForm1.Registered_Residence = Province.label + City.label + County.label + Town.label;
        this.dataForm1.RR_Province_Number = val[0];
        this.dataForm1.RR_City_Number = val[1];
        this.dataForm1.RR_County_Nubmer = val[2];
        this.dataForm1.RR_Town_Number = val[3];
      } else {
        this.dataForm1.Registered_Residence = '';
        this.dataForm1.RR_Province_Number = '';
        this.dataForm1.RR_City_Number = '';
        this.dataForm1.RR_County_Nubmer = '';
        this.dataForm1.RR_Town_Number = '';
      }
    },
    async handleSubmit() {
      const allValid = await this.validateAllForms();
      if (allValid) {
        this.loading = true;
        let ls_URL = window.location.href;
        const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
        let lJSONObject_Data_Options = new Object();
        //获取主表配置参数
        lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

        let ls_MainTableName = lJSONObject_Data_Options.TableName;
        let ls_DataForm = lJSONObject_Data_Options.form;
        let ls_primary_key = lJSONObject_Data_Options.primary_key;
        //没有子表下面内容就会报错，try/catch抛出异常
        try {
          //可能涉及多个子表
          document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
            let lJSONObject_ChildData_Options = new Object();
            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
            if (this[ls_DataForm][ls_primary_key]) {
              this[ls_ChildDataForm].forEach(item => {
                item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
              })
            }
            //建立子表结构体
            let JSONArray_ChildRecord = new Array();
            JSONArray_ChildRecord = this[ls_ChildDataForm];
            if (!this[ls_DataForm].Children) {
              this[ls_DataForm].Children = new Object();
            }
            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
          })
        } catch (error) {

        }
        //建立新增提交结构
        let lJSONObject_DataSet = new Object();
        if (action == 'Add') {
          if (this.nodeKey) {
            this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
          }
          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(this[ls_DataForm]);
          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
          lJSONObject_DataSet[action] = lJSONObject_Table;
        } else if (action == 'Modify') {
          const { add, modify } = this.deal(this[ls_DataForm]);
          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(modify);

          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

          lJSONObject_DataSet[action] = lJSONObject_Table;
          lJSONObject_DataSet['Add'] = new Object();
          if (add != null) {
            let lJSONArray_Record_Add = new Array();
            lJSONArray_Record_Add.push(add);

            let lJSONObject_Table_Add = new Object();
            lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

            lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
          }
        }
        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
        lJSONObject_DataSet['Add']['base_operation_log'] = [{
          Operation_Type: '0',
          Operation_Path: this.relativePath,
          Operation_Main,
          Operation_Interface:"generalSaveByRequestBody",
          Operation_IP: getIpAddress()
        }]
        submitSave(lJSONObject_DataSet, (res) => {
          this.loading = false;
          if (res.Status == 'success') {
            // window.location.href = './index.html'
            window.history.go(-1);
          }
        })
        // $.ajax({
        //   headers: requestHeaders(),
        //   url: `${mh}/generalBusiness/generalSaveByRequestBody`,
        //   method: "post",
        //   data: JSON.stringify({
        //     Data: lJSONObject_DataSet,
        //   }),
        //   success: (res) => {
        //     if (res.Status == 'success') {
        //       // window.location.href = './index.html'
        //       window.history.go(-1);
        //     }
        //   },
        //   complete: (XMLHttpRequest) => {
        //     this.loading = false;
        //     requestPretreatment(XMLHttpRequest)
        //   }
        // });
      }
    },
    getCategory() {
      console.log(1231);

      $.ajax({
        url: absolutepath() + "api/Nation.json",
        type: "GET",
        success: (data) => {
          this.Nation = data;
        },
        dataType: "json",
      });
      $.ajax({
        url: `${absolutepath()}api/Districtjl.json`,
        method: "get",
        success: (data) => {
          this.city = data;
        }
      });
      $.ajax({
        headers: requestHeaders(),
        type: "POST",
        url: mh + "/generalBusiness/generalQueryByTableName",
        data: {
          Data: "party_member_category", //指定要查询的数据库表名
          Condition: "Row_Status='0'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
        },
        success: (Result) => {
          this.Category = Result;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest)
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        type: "POST",
        url: mh + "/generalBusiness/generalQueryByTableNameWithOriginal",
        data: {
          Data: "personal_information", //指定要查询的数据库表名
          Condition: "Row_Status='0'", //定义查询条件，过滤 Row_Status 字段值为 0 的记录   查全部就定义为空
        },
        success: (Result) => {
          this.ID_Card = Result;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest)
        },
        dataType: "json",
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "post",
        data: {
          Data: "party_organization", //表名
          Condition: "Row_Status='0'",
        },
        success: (res) => {
          this.Manager = res;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest)
        },
      });
    },
    getData1() {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableName`,
        type: "POST",
        data: {
          Data: 'personal_tags',//商品类型表名称
          Condition: "Row_Status='0'"
        },
        success: function (data) {
          console.log(data);
          that.options = data; // 直接使用 this
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest)
        },
        dataType: "json"
      });
    }
  },

}


const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
app.component('yl-upload', ylUpload);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
